package com.jbit.utils;

import com.jbit.pojo.Menu;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 构建菜单树工具类
 */
public class MenuTreeBuilderUtil {

    public static List<Menu> build(List<Menu> menus) {
        List<Menu> formatMenus = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentId() == 0) {
                //一级菜单
                formatMenus.add(menu);
            }
        }
        //设置一级菜单的子菜单
        for (Menu menu : formatMenus) {
            menu.setChildren(getChildren(menu.getId(), menus));
        }
        //排序
        Collections.sort(formatMenus, Menu.sort());
        return formatMenus;
    }

    private static List<Menu> getChildren(Long id, List<Menu> menus) {
        List<Menu> childrenMenu = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentId() != 0) {
                if (menu.getParentId().equals(id)) {
                    //二级菜单
                    childrenMenu.add(menu);
                }
            }
        }
        Collections.sort(childrenMenu, Menu.sort());
        //把子菜单的菜单再次循环一遍  递归
        for (Menu menu : childrenMenu) {
            menu.setChildren(getChildren(menu.getId(), menus));
        }
        //退出递归
        if (childrenMenu.size() == 0) {
            return null;
        }
        return childrenMenu;
    }
}
